package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type DataController struct {
	beego.Controller
}
func init() {
	orm.RegisterModel(new(Data))
}
type Data struct {
	Id int
	Type string
	User_id int
	Data string `orm:"size(2550)"`
}
type Res struct {
	Code int
	Msg  string
	Data Data
}
func (this *DataController) Add() {
	o := orm.NewOrm()
	_type := this.GetString("type")
	_data := this.GetString("data")
	user_id, _ := this.GetInt("user_id")
	data := Data{Type: _type,Data:_data,User_id:user_id}
	id, err := o.Insert(&data)
	if err != nil {
		res := fail{0,"添加失败"}
		this.Data["json"] = res
	}else{
		res := success{0,"添加成功", strconv.FormatInt(id, 10)}
		this.Data["json"] = res
	}
	this.ServeJSON()
}

func (this *DataController) List() {
	status := this.GetString("status")
	o := orm.NewOrm()
	var users []User
	qs := o.QueryTable("user")
	qs.Filter("status", status).All(&users)
	//for i := 0; i < len(users); i++{
	//}
	for i , user := range users {
		if user.Status == "Y" {
			users[i].Status = "正常";
		}
	}
	res := List{0, users, "成功"}
	this.Data["json"] = res
	this.ServeJSON()
}


func (this *DataController) Item() {
	user_id, err := this.GetInt("user_id")
	_type := this.GetString("type")
	if err != nil {
		badRes := fail{1, "id不能为空"}
		this.Data["json"] = badRes
		this.ServeJSON()
		return
	}
	o := orm.NewOrm()
	var item Data
	o.QueryTable("data").Filter("user_id", user_id).Filter("type", _type).One(&item)
	var res Res
	if item.Id > 0{
		res.Data = item
		res.Code = 1
	}else{
		res.Code = 0
	}

	this.Data["json"] = res
	this.ServeJSON()
}


